import 'dart:async';
import 'package:flutter/material.dart';
import 'cooldown_interfaces.dart';

/// 优化后的防抖按钮
/// (节流按钮)：立即响应第一次点击，之后在冷却时间内忽略后续点击
class PDThrottleButton extends StatefulWidget {
  /// 按钮点击事件
  final VoidCallback? onPressed;

  /// 按钮子组件
  final Widget child;

  /// 防抖时间
  final Duration debounceDuration;

  /// 按钮样式
  final PDButtonType buttonType;

  /// 非自定义的按钮样式
  final ButtonStyle? buttonStyle;

  /// 冷却中的回调
  /// 参数[Duration]剩余冷却时间
  final DurationCallback? onCooldown;

  /// 冷却中的透明度
  final double cooldownOpacity;

  /// 日志处理器
  final CooldownLogger? logger;

  const PDThrottleButton({
    super.key,
    this.onPressed,
    required this.child,
    this.debounceDuration = const Duration(seconds: 2),
    this.buttonType = PDButtonType.customize,
    this.buttonStyle,
    this.onCooldown,
    this.cooldownOpacity = 0.6,
    this.logger,
  });

  @override
  State<PDThrottleButton> createState() => _PDThrottleButtonState();
}

class _PDThrottleButtonState extends State<PDThrottleButton> {
  DateTime? _lastPressedAt;
  Timer? _opacityTimer;

  @override
  void dispose() {
    _opacityTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Opacity child = Opacity(
      opacity: isInCooldown() ? widget.cooldownOpacity : 1.0,
      child: widget.child,
    );

    if (widget.buttonType == PDButtonType.elevated) {
      return ElevatedButton(
        onPressed: handleTap,
        style: widget.buttonStyle,
        child: child,
      );
    }
    return GestureDetector(onTap: handleTap, child: child);
  }

  /// 检查是否在冷却中
  bool isInCooldown() {
    if (_lastPressedAt == null) return false;
    return DateTime.now().difference(_lastPressedAt!) <=
        widget.debounceDuration;
  }

  /// 处理点击事件
  void handleTap() {
    if (isInCooldown()) {
      final int coolTime = widget.debounceDuration.inSeconds -
          DateTime.now().difference(_lastPressedAt!).inSeconds;
      widget.logger?.debug('按钮冷却中，剩余时间: $coolTime 秒');
      widget.onCooldown?.call(Duration(seconds: coolTime));
      return;
    }
    widget.onPressed?.call();
    setState(() {
      _lastPressedAt = DateTime.now();
    });

    // 添加定时器在冷却时间结束后更新界面
    _opacityTimer?.cancel();
    _opacityTimer = Timer(widget.debounceDuration, () {
      if (mounted) {
        setState(() {
          // 触发重建以更新透明度
        });
      }
    });
  }
}

/// 优化后的防抖按钮
/// (防抖按钮)：延迟响应点击，只有在指定时间内没有新点击时才触发
class PDDebounceButton extends StatefulWidget {
  /// 按钮点击事件
  final VoidCallback? onPressed;

  /// 按钮子组件
  final Widget child;

  /// 防抖时间
  final Duration debounceDuration;

  /// 按钮样式
  final PDButtonType buttonType;

  /// 非自定义的按钮样式
  final ButtonStyle? buttonStyle;

  /// 防抖中的透明度
  final double debounceOpacity;

  /// 日志处理器
  final CooldownLogger? logger;

  const PDDebounceButton({
    super.key,
    this.onPressed,
    required this.child,
    this.debounceDuration = const Duration(milliseconds: 500),
    this.buttonType = PDButtonType.customize,
    this.buttonStyle,
    this.debounceOpacity = 0.6,
    this.logger,
  });

  @override
  State<PDDebounceButton> createState() => _PDDebounceButtonState();
}

class _PDDebounceButtonState extends State<PDDebounceButton> {
  Timer? _debounceTimer;
  bool _isDebouncing = false;

  @override
  void dispose() {
    _debounceTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Opacity child = Opacity(
      opacity: _isDebouncing ? widget.debounceOpacity : 1.0,
      child: widget.child,
    );

    if (widget.buttonType == PDButtonType.elevated) {
      return ElevatedButton(
        onPressed: handleTap,
        style: widget.buttonStyle,
        child: child,
      );
    }
    return GestureDetector(onTap: handleTap, child: child);
  }

  /// 处理点击事件
  void handleTap() {
    widget.logger?.debug('防抖按钮被点击，重置防抖计时器');

    setState(() {
      _isDebouncing = true;
    });

    // 取消之前的计时器并重新开始计时
    _debounceTimer?.cancel();
    _debounceTimer = Timer(widget.debounceDuration, () {
      if (mounted) {
        setState(() {
          _isDebouncing = false;
        });
        widget.onPressed?.call();
      }
    });
  }
}
